//
//  CDLIstTableViewController.swift
//  DriverSchoolAPP
//
//  Created by Logel on 2017/5/18.
//  Copyright © 2017年 Logel. All rights reserved.
//

import UIKit

class CDLIstTableViewController: UITableViewController,CDListTableViewCellDelegate,LgCallBack {
    var pList = [NearBy]()
    var pageNo = 1
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshAutoNormalFooter()
    var selectNum = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        header.setRefreshingTarget(self, refreshingAction:#selector(self.headerRefresh))
        self.tableView.mj_header = header
        footer.setRefreshingTarget(self, refreshingAction:#selector(self.footerRefresh))
        self.tableView.mj_footer = footer
        getData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return pList.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseCell", for: indexPath) as! CDListTableViewCell
        cell.selectNum = indexPath.row
        cell.delegate = self
        // Configure the cell...
        cell.nb = pList[indexPath.row]
        return cell
    }
    
    func editCDListBtnClick(indexPath: Int,tag: Int) {
        switch tag {
        case 1:
            print("场地展示")
            selectNum = indexPath
            self.performSegue(withIdentifier: "toWeb", sender: nil)
        default:
           setPopView()
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toWeb" {
            let dest = segue.destination as! WebViewController
            dest.destUrl = WEB_URL + F_CGZS_URL + "?id=\(pList[selectNum].id)"
            dest.destTitle = "场地展示"
        }
    }
    
    
    func setPopView(){
        let bgView = UIView(frame: CGRect(x: 0, y: 0, width:KMainScreenWidth , height: KMainScreenHeight))
        bgView.backgroundColor = UIColor(red: 18/255.0, green: 18/255.0, blue: 18/255.0, alpha: 0.6)
        self.view.addSubview(bgView)
        bgView.tag = 9
        
        let av = UIView(frame: CGRect(x: 30, y: KMainScreenHeight/3, width: KMainScreenWidth-60, height: KMainScreenHeight/3))
        av.layer.cornerRadius = 15
        av.backgroundColor = UIColor.white
        av.tag = 9
        bgView.addSubview(av)
        
        let lab1 = UILabel(frame: CGRect(x: 10, y: 50, width: av.frame.size.width-20, height: 40))
        lab1.text = "咨询热线：\(KF_PHONE)"
        lab1.font = UIFont.systemFont(ofSize: 24)
        
        let lab2 = UILabel(frame: CGRect(x: 10, y: 91, width: av.frame.size.width-20, height: 40))
        lab2.text = "工作时间：9:00-18:00"
        lab2.font = UIFont.systemFont(ofSize: 24)
        av.addSubview(lab1)
        av.addSubview(lab2)
        
        let btnL = UIButton(frame: CGRect(x: 40, y: av.frame.size.height - 60, width: 90, height: 30))
        
        btnL.setTitle("呼叫", for: .normal)
        btnL.tintColor = UIColor.white
        btnL.backgroundColor = KP_MAIN_BLUE
        btnL.layer.cornerRadius = 5
        btnL.addTarget(self, action: #selector(callPhone), for: UIControlEvents.touchUpInside)

        av.addSubview(btnL)
        
        let btnR = UIButton(frame: CGRect(x: av.frame.size.width - 130, y: av.frame.size.height - 60, width: 90, height: 30))
        
        btnR.setTitle("取消", for: .normal)
        btnR.setTitleColor(UIColor.black, for: .normal)
        btnR.layer.borderColor = KP_MAIN_BLUE.cgColor
        btnR.layer.borderWidth = 1
        btnR.layer.cornerRadius = 5
        btnR.addTarget(self, action: #selector(cancelPop), for: UIControlEvents.touchUpInside)
        av.addSubview(btnR)
        
        
        
        
    }

    func cancelPop(){
        for x in self.view.subviews{
            if x.tag == 9 {
                x.removeFromSuperview()
            }
        }
    }
    
    func callPhone() {
        print("打电话")
        UIApplication.shared.openURL(NSURL(string: "tel://\(KF_PHONE)")! as URL)
    }
    func getData(){
        asyn_req_post(method:M_PlacesByAddress, cb: self, p: ["longitude":APP_lon as AnyObject,"latitude":APP_lat as AnyObject])
    }
    
    func callBack(method: String, data: AnyObject) {
        pList.removeAll()
        let json = JSON(data)
        print(json)
        let head = parseMobileHead(x: json["MobileHead"])
        if head.code == "1" {
            pList = parseNearByList(all: json["MobileBody"].arrayValue)
            self.tableView.reloadData()
            
        }else{
            showMsg(msg: "请在设置中打开定位，以便给您提供最好的服务。")
        }
        header.endRefreshing()
        footer.endRefreshing()
        
    }
    
    func headerRefresh(){
        print("下拉刷新.")
        sleep(1)
        pList.removeAll()
        //重现生成数据
        pageNo = 1
        getData()
        
    }
    
    func footerRefresh(){
        print("提拉加载")
        sleep(1)
        pageNo += 1
        getData()
    }
    
}
